
-- EliteMatchPanel 精英赛入口panel

local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local EliteMatchTaskRender = import("..renders.EliteMatchTaskRender")
local CrossServerEliteMatchHelper = import("..CrossServerEliteMatchHelper")
local UIUtil = require("app.utils.UIUtil")
local EliteMatchPanel = app.mvc.createPanelClass(...)

function EliteMatchPanel.createWithData(data, node)
    local sprite = EliteMatchPanel.extend(node or cc.CSLoader:createNode(Res.CrossServerEliteMatchPanel))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init()
    return sprite
end

function EliteMatchPanel.create(node)
    return EliteMatchPanel.createWithData(nil ,node)
end

function EliteMatchPanel:init(data)
    self.super.init(self, data)

    self._timeline = self:getTimeline()

    -- top
    self._topPanel = {}
    for i = 1, 2 do
        self._topPanel[i] = self._ui.Panel_Content:getChildByName("Panel_"..i)
        self._topPanel[i]:setVisible(false)
    end
    -- bottom
    -- self._bottomPanel = {}
    -- for i = 1, 3 do
    --     self._bottomPanel[i] = EliteMatchTaskRender.create(self._ui.Panel_bom:getChildByName("node_"..i))
    --     self._bottomPanel[i]:setVisible(false)
    -- end

    -- 宝箱
    self._bomPanel = self._ui.Panel_bom
    self.boxNode = self._bomPanel:getChildByName("Panel_icon")
    self.boxLoadingBar = self._bomPanel:findChild("bar/LoadingBar")
    self.boxExpNode = self._bomPanel:getChildByName("exp")
    self._boxIcon = self._bomPanel:findChild("Panel_icon/icon")
    display.uiAddClick(self._boxIcon, function()
        if self.haveNum and self.haveNum > 0 then --预览宝箱
            executeFunc(self._onOperate, "openBox")
        else -- 宝箱tips
            local dataTemp = GD:queryRestrictedRewardShowById(3)
            self:_showRareInfo(dataTemp, self._boxIcon)
        end
    end)

    self:registerViewEvent({
        {name = ViewEvent.CSElite_CrossCombatInfo, callback = handler(self, self.updateElitePanel)},
        -- {name = ViewEvent.Common_GetTaskReward, callback = handler(self, self.updateTaskNode)},
        {name = ViewEvent.CSElite_MyRankUpdate, callback = handler(self, self.updateMyRank)},
        {name = ViewEvent.CSElite_MatchStateUpdate, callback = handler(self, self.updateMatchState)},
    })
end

function EliteMatchPanel:updateElitePanel(eventName, info)
    if not info then return end
    self._playInfos = info.playInfo
    for i, v in ipairs(info.playInfo) do
        local panel = self._topPanel[i]
        if panel then
            panel:setVisible(true)
            -- node
            local openImg = panel:getChildByName("img_open")
            local closeImg = panel:getChildByName("img_close")
            local lockImg = panel:getChildByName("Image_lock")
            local tltNode = panel:getChildByName("tlt")
            local dateText = panel:getChildByName("date")
            local tipsText = panel:getChildByName("time")
            local rankPanel = panel:getChildByName("Panel_rang")
            local loadPanel = panel:getChildByName("Panel_load")
            local clickPanel = panel:getChildByName("click")
            -- data
            local isTodayOpen = v.isOpen -- 是否今日开放
            local isOpening = UD.csEliteMatch:isOpenByPlayId(v.playId) -- 是否在开放时间段内
            openImg:setVisible(isTodayOpen and isOpening)
            closeImg:setVisible(isTodayOpen and not isOpening)
            lockImg:setVisible(not isTodayOpen)
            tltNode:setString(table.concat({L(v.conf.name), string.format(L("EliteMatchTip1"), v.id)}, " "))
            local openTimeStr = os.date("%m.%d", v.startTime)
            local endTimeStr = os.date("%m.%d", v.endTime)
            dateText:setString(openTimeStr.."-"..endTimeStr)
            local tipsStr = CrossServerEliteMatchHelper:getTipsStr(v)
            tipsText:setString(tipsStr)
            local expConf = GD:getEliteMatchExp(v.lv, v.playId)
            if not expConf then return end
            if v.lv == 0 then
                rankPanel:setVisible(true)
                loadPanel:setVisible(false)
                local iconPath = string.format("%s%s.png", Res.eliteMatchPath, expConf.icon)
                rankPanel:getChildByName("btn_icon"):loadTexture(iconPath)
                rankPanel:getChildByName("tips"):setString(L("EliteMatchTip7"))
                rankPanel:getChildByName("btn_icon"):setTouchEnabled(true)
                rankPanel:getChildByName("btn_icon"):addTouchEventListener(function(sender, eventType)
                    if eventType == ccui.TouchEventType.ended then
                        -- tips
                        self:_showTips(rankPanel, v.playId, v.lv)
                    end
                end)
                rankPanel:getChildByName("btn_ranking"):setTouchEnabled(true)
                rankPanel:getChildByName("btn_ranking"):addTouchEventListener(function(sender, eventType)
                    if eventType == ccui.TouchEventType.ended then
                        UIHandler:handleMessage({id = Constant.FUNC_TYPE_RANK, mode = "open", rankingId = v.playId})
                    end
                end)
            else
                rankPanel:setVisible(false)
                loadPanel:setVisible(true)
                local iconPath = string.format("%s%s.png", Res.eliteMatchPath, expConf.icon)
                loadPanel:getChildByName("btn_icon"):loadTexture(iconPath)
                loadPanel:getChildByName("ranking"):setString(string.format(L("EliteMatchTip6"), v.lv))
                loadPanel:getChildByName("num"):setString(v.exp.."/"..expConf.levelupExp)
                loadPanel:getChildByName("LoadingBar"):setPercent(v.exp/tonumber(expConf.levelupExp)*100)
                loadPanel:getChildByName("btn_icon"):setTouchEnabled(true)
                loadPanel:getChildByName("btn_icon"):addTouchEventListener(function(sender, eventType)
                    if eventType == ccui.TouchEventType.ended then
                        --tips
                        self:_showTips(loadPanel, v.playId, v.lv)
                    end
                end)
            end
            if isTodayOpen then
                local initScale = panel:getScale()
                local scale = 0.02
                display.uiAddClick(
                    clickPanel,
                    function()
                        app:sendMsg("PvpEliteController", "openView", v.playId)
                    end,
                    false,
                    nil,
                    function(isTouch)
                        if isTouch then
                            panel:setScale(initScale - scale)
                        else
                            panel:runAction(cc.ScaleTo:create(0.05, initScale))
                        end
                    end)

                -- 默认打开tips
                if self._isShowTips then
                    local node = v.lv == 0 and rankPanel or loadPanel
                    self:_showTips(node, v.playId, v.lv)
                    self._isShowTips = false
                end
            end
            self:playEntranceAction(openImg, closeImg)
        end
        UD.csEliteMatch:C2S_WorldRankList(v.playId)
    end
    -- self:updateTaskNode()

    -- guide
	self:checkGuide()
end

-- function EliteMatchPanel:updateTaskNode(eventName, taskType, taskId)
--     local taskInfos = UD:getEliteMatchTasks()
--     local flag = true
--     for i = 1, #self._bottomPanel do
--         local taskNode = self._bottomPanel[i]
--         taskNode:setData(taskInfos[i])
--         if not taskInfos[i] then
--             if flag then
--                 taskNode:setTipsVisible(true)
--                 flag = false
--             else
--                 taskNode:setTipsVisible(false)
--             end
--         end
--         taskNode:setVisible(true)
--     end
-- end

-- 活动入口动画
function EliteMatchPanel:playEntranceAction(openImg, closeImg)
    openImg:stopAllActions()
    closeImg:stopAllActions()

    if openImg:isVisible() then
        local action = cca.repeatForever(cca.rotateBy(2, 360))
        openImg:runAction(action)
    end
    if closeImg:isVisible() then
        local action = cca.repeatForever(cca.rotateBy(2, 360))
        closeImg:runAction(action)
    end
end

-- 宝箱动画
function EliteMatchPanel:playAction()
    self._timeline:play("box", true)
end
function EliteMatchPanel:pauseAction()
    self._timeline:gotoFrameAndPause(0)
end

-- 更新我的排名
function EliteMatchPanel:updateMyRank(eventName, id, rank)
    if not id then return end
    if not self._playInfos then return end

    for i, v in ipairs(self._playInfos) do
        if v.playId == id then
            local panel = self._topPanel[i]
            local rankPanel = panel:getChildByName("Panel_rang")
            if rank == 0 then
                rankPanel:getChildByName("ranking"):setString(L("EliteMatchTip45"))
            else
                rankPanel:getChildByName("ranking"):setString(string.format(L("EliteMatchTip8"), rank))
            end            
        end
    end
end

-- 更新匹配状态
function EliteMatchPanel:updateMatchState(eventName, id)
    if not self._playInfos then return end

    for i, v in ipairs(self._playInfos) do
        if v.playId == id then
            local panel = self._topPanel[i]
            local tipsText = panel:getChildByName("time")
            local tipsStr = CrossServerEliteMatchHelper:getTipsStr(v)
            tipsText:setString(tipsStr)
        end
    end
end

----------------------- 宝箱/动画 start --------------------
-- 初始化宝箱信息
function EliteMatchPanel:refreshPvpBoxInfo()
    self.haveNum = UD:getArenaLuckBox()
    self.curPoint = UD:getPvpStarCount()
    self.maxPoint = UD:getLuckBoxLevelUpPoint(Enums.BoxType.pvp)
    self._curPointCount = self.curPoint + self.haveNum * self.maxPoint
    if UD:hasArenaLuckBoxCache() then -- 有宝箱数变化播放动画
        self:playBoxAction()
        UD:clearLuckBoxCacheByKey(Enums.lootType.arenaLuckBox) -- 取到缓存数据后要清掉
        UD:clearLuckBoxCacheByKey(Enums.lootType.starCount)
    else
        if UD:onlyArenaLuckBoxChange() then
            UD:clearLuckBoxCacheByKey(Enums.lootType.arenaLuckBox)
            self:performWithDelay(function()
                self:_playBoxArmature()
            end, 0.05)
        end
        self:_refreshBoxInfo()
    end
end

local boxNum = 0
local boxNumCache = 0
local playTimes = -1
local barStart = 0
local barEnd = 0
local startPer = 0
local endPer = 0
local per = 2
function EliteMatchPanel:playBoxAction()
    local pointCountCache = UD:getStarCountCache()
    local isBoxChange = pointCountCache and pointCountCache ~= self._curPointCount
    if isBoxChange then
        boxNum = math.floor(pointCountCache / self.maxPoint)
        boxNumCache = boxNum
        playTimes = self.haveNum - boxNum
        barStart = pointCountCache % self.maxPoint
        barEnd = playTimes > 0 and self.maxPoint or (barStart + self._curPointCount - pointCountCache)
        startPer = math.ceil(barStart * 100 / self.maxPoint)
        endPer = math.ceil(barEnd * 100 / self.maxPoint)
        self:_refreshBoxInfo(boxNum, barStart)

        self:playBoxBarAni()
    else
        self:_refreshBoxInfo()
    end
end

-- 播放经验条动画
function EliteMatchPanel:playBoxBarAni()
    self.boxLoadingBar:schedule(function()
        startPer = math.min(startPer + per, endPer)
        if playTimes < 0 then
            self.boxLoadingBar:stopAllActions()
        else
            if startPer == endPer then
                -- 达到最大值，修改宝箱个数
                boxNum = math.min(boxNum + 1, self.haveNum)
                playTimes = playTimes - 1
                barStart = playTimes < 0 and self.curPoint or 0
                barEnd = playTimes <= 0 and self.curPoint or self.maxPoint
                startPer = math.ceil(barStart * 100 / self.maxPoint)
                endPer = math.ceil(barEnd * 100 / self.maxPoint)
                self:_refreshBoxInfo(boxNum, barStart)
                if boxNumCache ~= boxNum then
                    self:_playBoxArmature()
                    boxNumCache = boxNum
                end
            else
                self.boxLoadingBar:setPercent(startPer)
                local point = math.floor(startPer / 100 * self.maxPoint)
                self.boxExpNode:setString(table.concat({point, "/", self.maxPoint}))
            end
        end
    end, 0.05)
end

-- 播放宝箱特效
function EliteMatchPanel:_playBoxArmature()
    if not self._inArmature then
        local params = {
            armatureName = "shaizibengchu",
            path = Res.ChessRollInEfcPath
        }
        local armature = Armature.create(params)
        local posX, posY = self.boxNode:getChildByName("Node_ani"):getPosition()
        self.boxNode:addChild(armature)
        armature:setPosition(posX, posY)
        armature:setScale(0.3, 0.3)
        self._inArmature = armature
    end
    self._inArmature:setVisible(true)
    self._inArmature:play("shaizibengchu", 1, function(sender)
        sender:setVisible(false)
        self:playBoxBarAni()
    end)
end

function EliteMatchPanel:_refreshBoxInfo(boxNum, point)
    if not boxNum then
        boxNum = self.haveNum
    end
    if not point then
        point = self.curPoint
    end
    local maxAccumulateBoxNum = tonumber( GD:getSystemPar( "arenaBoxAccumulateLimited", 20 ) ) -- 累积的上限
    -- 宝箱个数
    self.boxNode:findChild("bg_num/num"):setString(boxNum)
    self:_refreshBoxNumBg(boxNum > 0)
    self.boxNode:getChildByName("tips_max"):setVisible( maxAccumulateBoxNum <= boxNum )
    self._ui.tlt_2:setString(L("restrictedreward5_surface"))

    if 0 < boxNum then
        self:playAction()
    else
        self:pauseAction()
    end
    -- 经验条
    local percent = math.floor(point/self.maxPoint*100)
    self.boxLoadingBar:setPercent(percent)
    self.boxExpNode:setString(table.concat({point, "/", self.maxPoint}))
end

function EliteMatchPanel:_refreshBoxNumBg(isShow)
    local remainDayTimes = UD:getLuckBoxRestTimesByType(Enums.BoxType.pvp) --剩余每日开启次数
    local remainWeekTimes = UD:getLuckBoxWeeklyRestTimesByType(Enums.BoxType.pvp) -- 剩余每周开启次数
    local redBg = self.boxNode:findChild("bg_num/bg")
    local blackBg = self.boxNode:findChild("bg_num/bg_1")
    if isShow then
        if remainDayTimes > 0 and remainWeekTimes > 0 then
            redBg:setVisible(true)
            blackBg:setVisible(false)
        else
            redBg:setVisible(false)
            blackBg:setVisible(true)
        end
    end
    self.boxNode:getChildByName("bg_num"):setVisible(isShow)
    self.boxNode:getChildByName("mask"):setVisible(not isShow)
    self.boxNode:getChildByName("lock"):setVisible(not isShow)
end

-- 展示上方宝物具体信息
function EliteMatchPanel:_showRareInfo( dataTemp, triggerNode )
    if self._rareInfoPanel then
        self._rareInfoPanel:setData( dataTemp )
    else
        self._rareInfoPanel = NewRareInfoView.create()
        self._rareInfoPanel:setData( dataTemp )
        self._ui["Panel"]:addChild( self._rareInfoPanel )

        -- 点击空白区域关闭
        display.nodeRemoveForNotHit(self._rareInfoPanel, function()
            if self._rareInfoPanel then
                self._rareInfoPanel:removeFromParent()
                self._rareInfoPanel = nil
            end
        end)
    end

    local triggerNodeBoundingBox = triggerNode:getBoundingBox()
    local worldPosTemp = triggerNode:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
    triggerNodeBoundingBox.x = worldPosTemp.x
    triggerNodeBoundingBox.y = worldPosTemp.y
    display.adjustNodePos( triggerNodeBoundingBox, self._rareInfoPanel )
end
----------------------- 宝箱/动画 end --------------------

-- 检查是否有引导
function EliteMatchPanel:checkGuide()
    local funcId = Constant.FUNC_TYPE_CS_ELITEMATCH
	local params = {
		scene = funcId,
		sceneSelf = self,
		getFunc = self.getGuideNodeFunc,
		nextFunc = self.checkGuide
	}
	EM:notify("checkGuide", params)
end

function EliteMatchPanel:getGuideNodeFunc(id)
    if not self:isVisible() then return end
    if not self._playInfos then return end

    if id == 531 then
        local curPlayId = UD.csEliteMatch:getOpenPlayId()
        for i, v in ipairs(self._playInfos) do
            if v.playId == curPlayId then
                return self._topPanel[i]:getChildByName("click")
            end
        end
    end
end

-- 打开界面时是否显示赛季奖励tips
function EliteMatchPanel:isShowTips(b)
    self._isShowTips = b
end

function EliteMatchPanel:_showTips(node, id, lv)
    if cc.isDead(node) then return end
    if not id or not lv then return end

    local dataTemp = {
        name = L("secretDungeontips5"),
        desc = (id == Enums.TeamTarget.eliteMatchArena) and L("EliteMatchTip18") or L("EliteMatchTip19"),
        notice = L("tips_3000412")
    }
    dataTemp.rewards = CrossServerEliteMatchHelper:getSeasonReward(id, lv)
    UIUtil.showBoxTipsView(self, node:getChildByName("btn_icon"), dataTemp)
end

return EliteMatchPanel